// pages/cookbook/cookbook.js
const GetPeriod = require("../../utils/getperiod.js");
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    currentTab: 0,
    showflag: true,
    content: null,
    dateStart: null,
    dateEnd: null,
    now: null,
    dates: null,
    num: 0,
    week: null,
    year: null,
    type: 0,
    leftDay: "2020-08-06",
    rightDay: "2020-08-06",
    cookbookaddrole: 0,
    status: null
  },
  // 点击上一周
  prevWeek: function (e) {
    this.data.num = this.data.num - 7;
    this.getWeekStartDate(this.data.num);
  },
  // 点击下一周
  nextWeek: function (e) {
    this.data.num = this.data.num + 7;
    this.getWeekStartDate(this.data.num);

  },
  getweekString: function (date1) {
    var Date1 = new Date(date1)
    var y = Date1.getFullYear()
    var Date2 = new Date(y + "/1/1")
    console.log(Date2)
    var dayOfWeek = Date2.getDay();
    //如果把周日算在一周的最后一天，请加上下面这句
    dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek
    //如果把周日算在一周的第一天，请删除上面这句
    var num = (Date1 - Date2) / 1000 / 3600 / 24
    var whichWeek = Math.ceil((num + dayOfWeek) / 7)
    this.setData({
      week: whichWeek - 1
    })

    console.log("您查询的日期在本年度的第" + whichWeek + "周！")
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    var that = this;
    that.getWeekStartDate(0)
    /**
     * 获取当前设备的宽高
     */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }

    });
  },


  //获取本周的开始日期
  getWeekStartDate(numDay) {
    let that = this;
    this.now = new Date();
    this.nowYear = this.now.getYear(); //当前年 
    this.nowMonth = this.now.getMonth(); //当前月 
    this.nowDay = this.now.getDate(); //当前日 
    this.nowDayOfWeek = this.now.getDay(); //今天是本周的第几天 
    this.nowYear += (this.nowYear < 2000) ? 1900 : 0;
    var a = new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 1 + numDay);
    let dateStart = ""
    let dateEnd = ""
    if (this.nowDayOfWeek == 0) {
      dateStart = GetPeriod.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 1 + numDay - 7));
      dateEnd = GetPeriod.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 7 + numDay - 7));
    } else {
      dateStart = GetPeriod.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 1 + numDay));
      dateEnd = GetPeriod.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 7 + numDay));

    }

    // console.log(dateStart)
    // 获取今天日期
    let now = GetPeriod.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay));
    now = now.replace(/-/g, "/");
    now = now.substring(5);
    this.setData({
      dateStart: dateStart,
      dateEnd: dateEnd,
      now: now,
      dates: now,
      year: a.getFullYear()
    })
    this.getweekString(dateStart);
    // 初始化数据(历史纪录)
    var timestamp = Date.parse(new Date(this.data.dateStart));
    timestamp = timestamp / 1000;
    // console.log(timestamp);
    that.setData({
      timestamp: timestamp,
    })
    this.getData()

  },
  // 点击上一周
  prevWeek: function (e) {
    this.data.num = this.data.num - 7;
    this.getWeekStartDate(this.data.num);
  },
  // 点击下一周
  nextWeek: function (e) {
    this.data.num = this.data.num + 7;
    this.getWeekStartDate(this.data.num);

  },

  getData: function (e) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "weekOrder": this.data.week,
      "year": this.data.year,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileType": 1,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "get_cookbook"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);

        that.setData({
          status: res.data.status
        })

        if (res.data.status == 0) {
          var content = res.data.data;
          var rows = 0;
          if(res.data.dishes!=null){
            if (res.data.type == 1) {
              if (content.length > 0) {
                for (var i = 0; i < content.length; i++) {
                  var length = 0
                  for (var j = 0; j < content[i].mdata.length; j++) {
                    length += content[i].mdata[j].meal_list.length
                  }
                  if (length > rows) {
                    rows = length
                  }
                }
                if (rows > 0) {
                  that.setData({
                    winHeight: ((rows / 2) + (rows % 2)) * 400 + 200
                  })
                }
              }
            }
          }

          that.setData({
            content: content,
            leftDay: res.data.leftDay,
            rightDay: res.data.rightDay,
            cookbookaddrole: res.data.cookbookaddrole,
            type: res.data.type
          })
        }

      },
      fail: function (res) {},
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },


  //  tab切换逻辑
  swichNav: function (e) {
    if (this.data.currentTab == e.target.dataset.current) {
      return false;
    } else {
      var that = this;
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  bindChange: function (e) {

    var that = this;
    that.setData({
      currentTab: e.detail.current
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  addcookbook: function () {
    wx.navigateTo({
      url: '../addcookbook/addcookbook?num='+this.data.num,
    })
  }
})